import { login, getProfile, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router/index'

const state = {
  token: getToken() || '',
  profile: null
}
const mutations = {
  setToken(state, data) {
    setToken(data)
    state.token = data
  },
  setProfile(state, data) {
    state.profile = data
  },
  removeUserInfo(state) {
    state.profile = null
    state.token = ''
    removeToken('hrToken')
  }

}
const actions = {
  async login(store, data) {
    const res = await login(data)
    localStorage.setItem('logintime', Date.now())
    store.commit('setToken', res)
  },
  async getProfile(store) {
    const res = await getProfile()
    console.log(res)
    const userDetail = await getUserDetailById(res.userId)
    console.log(userDetail)
    store.commit('setProfile', { ...res, ...userDetail })
  },
  logout(store) {
    store.commit('removeUserInfo')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
